/**
 * Copyright (c) 2015-2020, ShangRao Institute of Big Data co.,LTD and/or its
 * affiliates. All rights reserved.
 */
package cn.ibdsr.human.service.impl;


import cn.ibdsr.human.constant.GunsExceptionEnum;
import cn.ibdsr.human.exception.FastdfsException;
import cn.ibdsr.human.service.FdfsClientService;
import cn.ibdsr.human.service.ImageService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Description 类功能和用法的说明
 * @Version V1.0
 * @CreateDate 2018/4/10 14:59
 *
 * Date           Author               Description
 * ------------------------------------------------------
 * 2018/4/10      ZhangLin               类说明
 *
 */

@Service("imageService")
public class ImageServiceImpl implements ImageService {

    /**日志*/
    protected static final Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);

    @Autowired
    private FdfsClientService fdfsClientService;

    @Override
    public String upload(MultipartFile imageFile) {
        try {
            if (imageFile == null || imageFile.getBytes().length == 0) {
                LOGGER.error("上传文件内容为空");
                return null;
            }
            return fdfsClientService.uploadFile(imageFile.getBytes(),
                    FilenameUtils.getExtension(imageFile.getOriginalFilename()));
        } catch (IOException io) {
            LOGGER.error("上传文件出错, 获取原文件内容出错".
                    concat(", 原因是" + io.getMessage()), io);
            return null;
        }
    }

    @Override
    public String upload(String url) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet method = new HttpGet(url);
            HttpResponse result = httpClient.execute(method);
            /**http响应不成功*/
            if (result.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            int dotIndex = url.lastIndexOf(".");
            String extendName = dotIndex != -1? url.substring(dotIndex+1) : "jpg";
            return fdfsClientService.uploadFile(IOUtils.toByteArray(result.getEntity().getContent()), extendName);
        } catch (IOException io) {
            LOGGER.error( "上传网络文件出错, 获取原文件内容出错".
                    concat(", 原因是" + io.getMessage()), io);
            return null;
        }
    }

    @Override
    public void delete(String path) {
        try {
            fdfsClientService.deleteFile(path);
        } catch (Exception e) {
            /**捕获所有底层异常*/
            throw new FastdfsException(GunsExceptionEnum.FILE_DELETE_NOT_FOUND, "文件路径".concat(path));
        }
    }
}
